package cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.common;

import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.reflection.QueryReflection;

import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;

public class SetCurrentDateTimeFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Object instance = flowContext.checkData("instance");
        Property property = flowContext.checkInstanceData(Property.class);

        Field field = QueryReflection.newQuery(instance.getClass())
                .execute()
                .getField(property.name);
        try {
            Object value = field.get(instance);
            //当用户手动设置该字段时,则程序不再注入时间
            if (null != value) {
                return;
            }
            switch (property.className) {
                case "java.util.Date": {
                    field.set(instance, new java.util.Date(System.currentTimeMillis()));
                }
                break;
                case "java.sql.Date": {
                    field.set(instance, new Date(System.currentTimeMillis()));
                }
                break;
                case "java.sql.Timestamp": {
                    field.set(instance, new Timestamp(System.currentTimeMillis()));
                }
                break;
                case "java.util.Calendar": {
                    field.set(instance, Calendar.getInstance());
                }
                break;
                case "java.time.LocalDate": {
                    field.set(instance, LocalDate.now());
                }
                break;
                case "java.time.LocalDateTime": {
                    field.set(instance, LocalDateTime.now());
                }
                break;
                default: {
                    throw new IllegalArgumentException("不支持该日期类型,目前支持的类型为Date,Calendar,LocalDate,LocalDateTime!当前类型:" + property.className);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("设置当前时间异常", e);
        }
    }

    @Override
    public String name() {
        return "设置当前时间";
    }
}
